package cn.imatu.framework.knife4j.micro.servlet;

import cn.hutool.core.util.StrUtil;
import cn.imatu.framework.tool.core.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.GroupedOpenApi;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;

/**
 * @author shenguangyang
 */
@Slf4j
@Data
public class GroupedOpenApiFactoryBean implements FactoryBean<GroupedOpenApi>, InitializingBean, ApplicationContextAware {

    private String beanName;
    private ApiGroupConfig apiDocket;
    private Environment environment;
    private String basePackage;

    @Override
    public GroupedOpenApi getObject() throws Exception {
        try {
            String groupName = StringUtils.firstNonEmpty(apiDocket.groupName(), environment.getProperty("spring.application.name"));
            if (StrUtil.isEmpty(groupName)) {
                return null;
            }
            boolean enable = Boolean.parseBoolean(environment.getProperty("knife4j.enable", "false"));
            log.info("开始动态注册 knife4j-docket, enable: {}, groupName: {}, apiPackage: {}", enable, groupName, basePackage);
            return GroupedOpenApi.builder().group(groupName)
                .pathsToMatch("/**").pathsToExclude("/error").packagesToScan(basePackage)
                .build();
        } catch (Exception e) {
            log.error("[knife4j] 创建接口摘要失败, error: ", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public Class<?> getObjectType() {
        return GroupedOpenApi.class;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {

    }
}
